<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="workSheetTypeId">
        <el-select v-model="queryParams.workSheetTypeId" filterable placeholder="请选择工单类型" clearable style="width: 145px">
          <el-option
            v-for="dict in workSheetTypeList"
            :key="dict.id"
            :label="dict.sheetTypeName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="stationId">
        <el-select v-model="queryParams.stationId" placeholder="请选择场站" clearable style="width: 145px" @change="handleStation">
          <el-option
            v-for="dict in stationList"
            :key="dict.id"
            :label="dict.stationName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="deviceId">
        <el-select v-model="queryParams.deviceId" clearable class="labelWidth" filterable placeholder="请选择设备" style="width: 145px">
          <el-option
            v-for="item in deviceList"
            :key="item.deviceId"
            :label="item.deviceName"
            :value="item.deviceId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="sheetStatus">
        <el-select v-model="queryParams.sheetStatus" filterable placeholder="请选择进度" clearable style="width: 145px">
          <el-option
            v-for="dict in workSheetStatusList"
            :key="dict.id"
            :label="dict.info"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="" prop="workSheetName">
        <el-input
          style="width: 150px"
          v-model="queryParams.workSheetName"
          placeholder="请输入工单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="" prop="auto">
        <el-select v-model="queryParams.auto" class="labelWidth" clearable style="width: 100px"
                   placeholder="模式">
          <el-option
            key="0"
            label="手动"
            value="0">
          </el-option>
          <el-option
            key="1"
            label="自动"
            value="1">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="currentConsumerName">
        <el-input
          style="width: 150px"
          v-model="queryParams.currentConsumerName"
          placeholder="请输入处理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="timeExport">
        <el-date-picker
          v-model="queryParams.timeExport"
          :default-time="['00:00:00', '23:59:59']"
          :picker-options="pickerOptions"
          align="right"
          clearable
          end-placeholder="充电结束日期"
          range-separator="至"
          start-placeholder="充电开始日期"
          style="width: 240px"
          type="daterange"
          value-format="timestamp"
          @change="timeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:workSheet:add']"
        >新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['business:workSheet:edit']"
              >修改</el-button>
            </el-col>-->
      <!--      <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['business:workSheet:remove']"
              >删除</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:workSheet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workSheetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="id"/>-
      <el-table-column label="工单名称" align="center" prop="workSheetName"/>
      <el-table-column label="创建时间" width="150px" align="center" prop="creatTime">
        <template v-slot="scope">
          {{ parseTime(scope.row.creatTime) }}
        </template>
      </el-table-column>
      <el-table-column label="工单类型" align="center" prop="sheetTypeName"/>

      <el-table-column label="处理模式" align="center" prop="auto">
        <template slot-scope="scope">
          <el-tag :type="scope.row.auto==1?'success':'danger'">{{
              scope.row.auto == 1 ? '自动' : '手动'
            }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="进度" align="center" prop="sheetStatus">
        <template v-slot="scope">
          {{ sheetStatus[scope.row.sheetStatus] }}
        </template>
      </el-table-column>
      <el-table-column label="场站" align="center" prop="stationName"/>
      <el-table-column label="设备名称" align="center" prop="deviceName"/>
      <el-table-column label="当前处理人" align="center" prop="nickName"/>

<!--      <el-table-column label="设备ID" align="center" prop="deviceId"/>-->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            :class="['text-button', { 'active': active===scope.$index+'handleUpdate' }]"
            type="text"
            @click="handleUpdate(scope.row),active=scope.$index+'handleUpdate'"
            icon="el-icon-wallet"
            v-hasPermi="['business:workSheet:edit']"
          >工作台
          </el-button>
          <!--          <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['business:workSheet:edit']"
                    >修改
                    </el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['business:workSheet:remove']"
                    >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-descriptions class="margin-top" title="" :column="4" border>
        <el-descriptions-item>
          <template slot="label">
            订单是否自动
          </template>
          <el-tag :type="this.form.auto==1?'success':'danger'">{{
              this.form.auto == 1 ? '自动' : '手动'
            }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            创建时间
          </template>
          {{ parseTime(this.form.creatTime) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            工单处理记录ID
          </template>
          {{ this.form.currentRecordId }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            状态
          </template>
          {{ sheetStatus[this.form.sheetStatus] }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            场站
          </template>
          {{ this.form.stationName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            工单名称
          </template>
          {{ this.form.workSheetName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            工单类型
          </template>
          {{ this.form.sheetTypeName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            当前处理人
          </template>
          {{ this.form.nickName }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            设备ID
          </template>
          {{ this.form.deviceId }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            设备名称
          </template>
          {{ this.form.deviceName }}
        </el-descriptions-item>
      </el-descriptions>
      <el-table v-loading="loading" :data="recordsList" style="margin-top: 20px">
        <!--        <el-table-column label="主键" align="center" prop="id" />-->
        <el-table-column label="文件记录" align="center" prop="fileRemarks"/>
        <!--        <el-table-column label="工单接收人" align="center" prop="nextSourceConsumerId" />-->
        <el-table-column label="工单接收人名称" align="center" prop="nextSourceConsumerName"/>
        <el-table-column label="文本记录" align="center" prop="remarks"/>
        <el-table-column label="通知人" align="center" prop="sourceConsumerId"/>
        <el-table-column label="工单来源" align="center" prop="sourceName"/>
        <el-table-column label="工单ID" align="center" prop="workSheetId"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="submitForm">结束</el-button>
        <el-button @click="cancel">退出工作台</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWorkSheet,
  getWorkSheet,
  delWorkSheet,
  addWorkSheet,
  updateWorkSheet,
  getWorkSheetStatus
} from "@/api/business/workSheet";
import {getAllChargeStation, getAllDeviceByStationId,} from "@/api/business/station";
import {listRecords} from "@/api/business/records";

import {parseTime} from "@/utils/ruoyi";
import {getWorkSheetTypeAll} from "@/api/business/workSheetType";

const sheetStatus = [
  '预创建工单',
  '已指派',
  '已指派已提醒'
]
export default {
  name: "WorkSheet",
  data() {
    return {
      active: null,
      recordsList: [],
      sheetStatus,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单表格数据
      workSheetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auto: null,
        creatTime: null,
        currentRecordId: null,
        deviceId: null,
        sheetStatus: null,
        stationId: null,
        workSheetName: null,
        workSheetTypeId: null,
        currentConsumerId: null,
        currentConsumerName:null,
        deviceName: null,
        timeExport:[],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      stationList: [],
      deviceList:[],
      workSheetTypeList:[],
      workSheetStatusList:[],
      pickerOptions: {
        disabledDate(time) {
          const date = new Date("2022-12-31 ");
          return time.getTime() < date.getTime();     //禁止选取当天之后的日期（不包括静止当天）
        },
        shortcuts: [{
          text: '最近一个月',
          onClick(picker) {
            const now = new Date();
            const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
            const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        },
          {
            text: '最近两个月',
            onClick(picker) {
              const now = new Date();
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 60);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const now = new Date();
              const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
              const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
    };
  },
  created() {
    this.one()
    this.getList();
    this.getListStation()
    this.getWorkSheetTypeAll()
    this.getWorkSheetStatus()
  },
  methods: {
    //最近一个月
    one() {
      const now = new Date();
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 59);
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      this.queryParams.beginTime = start
      this.queryParams.endTime = end
      this.queryParams.timeExport = [start, end]
    },
    timeChange(val) {
      if (!val) return
      this.queryParams.beginTime = val[0]
      this.queryParams.endTime = val[1]
    },
    handleStation(event) {
      this.deviceList = null
      this.queryParams.deviceId = ''
      this.getAllDeviceByStationId(event)
    },
    async getAllDeviceByStationId(id) {
      let res = await getAllDeviceByStationId(id)
      this.deviceList = res.rows
    },
    async getWorkSheetStatus(){
      try {
        let res = await getWorkSheetStatus()
        this.workSheetStatusList = res.data
      }catch (e) {

      }
    },
    async getWorkSheetTypeAll (){
      try {
        let res = await getWorkSheetTypeAll()
        this.workSheetTypeList = res.data
      }catch (e) {

      }
    },
    getListRecords() {
      this.loading = true;
      listRecords({pageNum: 1, pageSize: 100, workSheetId: this.form.id}).then(response => {
        this.recordsList = response.rows;
        this.loading = false;
      });
    },
    /** 查询场站列表 **/
    async getListStation() {
      let res = await getAllChargeStation()
      this.stationList = res.data;
      console.log(res)
    },
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listWorkSheet(this.queryParams).then(response => {
        this.workSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        auto: null,
        creatTime: null,
        currentRecordId: null,
        deviceId: null,
        sheetStatus: null,
        stationId: null,
        workSheetName: null,
        workSheetTypeId: null,
        currentConsumerId: null,
        deviceName: null
      };
      this.resetForm("form");
      this.recordsList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "工单工作台";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkSheet(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "工单工作台";
        this.getListRecords()
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWorkSheet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWorkSheet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工单编号为"' + ids + '"的数据项？').then(function() {
        return delWorkSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/workSheet/export', {
        ...this.queryParams
      }, `workSheet_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
